﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Columbus
{
    [DataContract]
    public class ViewState : IViewState
    {
        public const string KeyPattern = "ViewStateFor{0}.dat";

        private readonly string fileIdentifier;

        [DataMember]
        public string ViewName { get; set; }

        [DataMember]
        public string ViewModelTypeName { get; set; }

        [DataMember]
        public readonly Dictionary<string, object> State = new Dictionary<string, object>();

        [DataMember]
        public readonly Dictionary<string, object> ConstructionData = new Dictionary<string, object>();

        public ViewState(string viewName, string fileIdentifier, string viewModelTypeName = "")
        {
            this.fileIdentifier = fileIdentifier;
            ViewName = viewName;
            ViewModelTypeName = viewModelTypeName;
        }

        public void SaveConstructorParameter(string key, object value)
        {
            ConstructionData.Add(key, value);
        }

        public void Save(string key, object value)
        {
            State.Add(key, value);
        }

        public object Get(string key)
        {
            return State[key];
        }

        public IEnumerable<string> PropertyNames
        {
            get { return State.Keys; }
        }

        public IEnumerable<object> PropertyValues
        {
            get { return State.Values; }
        }

        public IEnumerable<string> ConstructorParameterNames
        {
            get { return ConstructionData.Keys; }
        }

        public IEnumerable<object> ConstructorParameterValues
        {
            get { return ConstructionData.Values; }
        }

        public object GetConstructorParameter(string key)
        {
            return ConstructionData[key];
        }

        public bool HasViewModel
        {
            get { return !String.IsNullOrEmpty(ViewModelTypeName); }
        }

        public void Persist(ITransientStore transientStore, params Type[] knownTypes)
        {
            transientStore.Save(this, String.Format(KeyPattern, fileIdentifier), knownTypes);
        }
    }
}